package com.yuven.appframework.util;

import android.app.ActivityManager;
import android.content.Context;
import android.text.TextUtils;

import java.util.List;

public class ProcessUtil {

    public static String getCurrentProcessName(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> rapis = am.getRunningAppProcesses();
        if(rapis == null){
            rapis = am.getRunningAppProcesses();
        }
        if(rapis!=null) {
            for (ActivityManager.RunningAppProcessInfo rapi : rapis) {
                if(rapi.pid == android.os.Process.myPid()){
                    return rapi.processName;
                }
            }
        }
        return null;
    }

    public static String getForgroundProcessName(Context context) {
        String result="";
        try {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> rapis = am.getRunningAppProcesses();
            if (rapis == null) {
                rapis = am.getRunningAppProcesses();
            }
            if (rapis != null) {
                for (ActivityManager.RunningAppProcessInfo rapi : rapis) {
                    if (rapi.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        result = rapi.processName;
                        break;
                    }
                }
            }
        }catch (Exception e){
            result = "";
        }
        return result;

    }


    //判断进程是否存活
    public static boolean isProcessExit(Context context,String processName){
        if(TextUtils.isEmpty(processName))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> rapis = am.getRunningAppProcesses();
        if(rapis == null){
            rapis = am.getRunningAppProcesses();
        }
        if(rapis!=null) {
            for (ActivityManager.RunningAppProcessInfo rapi : rapis) {
                if (processName.equals(rapi.processName)) {
                    return true;
                }
            }
        }
        return false;
    }
}
